<template>
  <div>
    <!-- action后台接收地址
      how-file-list 是否显示上传列表
on-success 上传成功触发
before-upload 上传之前
 http-request 自定义上传函数（自己写发请求上传的逻辑）
    -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="staffPhoto" :src="staffPhoto" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProcess" status="success" type="line" :percentage="percentage"></el-progress>
    </el-upload>
  </div>
</template>

<script>
// 导入cos的SDK调用
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDIPGvJQGq9BwRgdJjtqWv5yav0oLbaIjt', // 身份识别ID
  SecretKey: 'uYv1pNeeOr40f3B3ey2oJXVBaiZ9SVHm' // 身份秘钥
})
export default {
  name: 'Uploadimg',
  props: {
    staffPhoto: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imageUrl: '',
      percentage: 0,
      showProcess: false
    }
  },
  methods: {
    // 自定义上传的回调函数
    upload (params) {
      // console.log(params)
      this.showprogree = true
      // 后续调用腾讯云cos后台接口上传图片
      cos.putObject({
        Bucket: 'tao-1308304234', /* 必须  桶的名称*/
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: function (progressData) {
          // 上传进度（数值%）
          // 上传进度（0-1）=》progressData.percent的值 =》0.0 => 0.1 ... => 0.9 1
          // console.log(progressData.percent * 100)
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // 注意这里要把函数改成箭头函数，不然this拿不到上面的变量
        console.log(err, data)
        if (!err) {
          // 上传成功
          // 显示上传成功后的图片
          setTimeout(() => {
            this.$emit('update:staffPhoto', `http://${data.Location}`)
            this.percentage = 0
            this.showprogree = false
          }, 800)
        }
      })
    },
    // handleAvatarSuccess (res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw)
    // },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
